<?php

namespace app\admin\controller;

use think\facade\Cache;
use think\Controller;
use think\Request;
use think\facade\Session;
use app\admin\model\AdminRoleModel;
use app\admin\model\AdminMenuModel;

class Base extends Controller
{
    public function initialize()
    {
        //是否登录
        $username = Session::get('username');
        if (empty($username)) {
            $this->error('请先登录后访问', url('admin/login/index'));
        }

        //判断是否有权限访问
        if (1 != Session::get('role_id')) {
            $res = $this->isNoAuth();
            if ($res['status'] == 'n') {
                if ($this->request->isAjax()) {
                    echo json_encode($res);
                    exit;
                } else {
                    exit('<div style="margin: 0 auto;display: table;font-size: 18px;color: red;">你没有访问权限！</div>');
                }
            }
        }
    }

    public function isNoAuth()
    {
        $admin_menu_model = new AdminMenuModel;
        $admin_role_model = new AdminRoleModel;
        //取出当前用户的权限id str
        $role_id = Session::get('username_role_id');
        if (!Cache::get('role' . $role_id)) {
            $auth_id = $admin_role_model->field('auth')->find($role_id);
            $menu = $admin_menu_model->where([['id', 'in', $auth_id['auth']], ['status', '=', 1]])->select();
            $auth = [];
            if (!$menu->isEmpty()) {
                $menu = $menu->toArray();
                foreach ($menu as $k => $v) {
                    $auth[strtolower($v['url'])] = $v['status'];
                }
            }
            Cache::set('role' . $role_id, $auth);
        } else {
            $auth = Cache::get('role' . $role_id);
        }
        //是否有权限访问
        $a = preg_match('/(admin.*)\./', $_SERVER['REQUEST_URI'], $m);
        if ($a) {
            if (empty($auth[strtolower($m[1])])) {
                return ['status' => 'n', 'info' => '没有访问权限'];
            }
        }
    }
}
